<?php

namespace app\common\lib\message;

use think\Exception;
use think\facade\Cache;
use think\api\Client;

class Sms
{

    public const BIND = 'bind';
    public const LOGIN = 'login';
    public const REGISTER = 'register';
    public const VERIFY = 'verify';
    public $sign = '';

    public const SCENE = [
        'login' => [
            'title' => '登录验证码通知',
            'content' => '您正在登录#SIGN#，你的验证码是:%s,此验证码10分钟内有效',
            'templateId' => '5',
        ],
    ];

    public function __construct(string $signName = '一个短网址')
    {
        $this->sign = $signName;
    }


    public function sendVerifyCode(string $target,string $scene){
        if(!preg_match("/^1[34578]\d{9}$/", $target)){
            throw new Exception('手机号码格式错误');
        }
        #TODO:存储ip，生成时间校验频率
        $code = rand(0000,9999);
        $sceneData = self::SCENE[$scene];

        $client = new Client(env('thinkapi.appcode'));
        $result = $client->smsSend()
            ->withSignId(323)
            ->withTemplateId($sceneData['templateId'])
            ->withPhone($target)
            ->withParams(json_encode(['code'=>$code]))
            ->request();

        if($result['code'] == 0){
            Cache::set('sms_code_'.$target,$code);
            return true;
        }else{
            throw new Exception($result['message']);
        }
    }
}
